const baseWidth = window.screen.availWidth - 59;
const ONE_DAY_HOURS = 24;
const ONE_HOUR_MINUTES = 60;
const ONE_DAY_MINUTES = 24 * 60;

const calculateWidth = (times) => {
	const widths = [];

	translateToArray(times).forEach(time => {
		const [start, end] = time.split('-');
		const proportion = calculateProportion(start, end);

		widths.push(baseWidth * proportion)
	})

	return widths
}

const calculateOffset = (times) => {
	const offsets = [];

	translateToArray(times).forEach(time => {
		const [start, end] = time.split('-');
		const [startScale, endScale] = start.split(':');
		const totalMinutes = parseInt(startScale) * ONE_HOUR_MINUTES + parseInt(endScale);
		offsets.push((totalMinutes / ONE_DAY_MINUTES) * baseWidth);
	});

	return offsets;
}

const calculateProportion = (start, end) => {
	const hour_minute = [];

	start.split(':').forEach((startScale, index) => {
		const endScale = end.split(':')[index];
		hour_minute.push(parseInt(endScale) - parseInt(startScale));
	});

	const [hours, minutes] = hour_minute;

	return (hours * ONE_HOUR_MINUTES + minutes) / ONE_DAY_MINUTES;
}

const calculateRestWidth = (scheduleWidths, scheduleOffsets) => {
	const hasRestPeriod = (scheduleWidths.length > 1);

	if (hasRestPeriod) {
		const restWidths = scheduleWidths.map((width, index) => {
			const offset = scheduleOffsets[index];
			const nextOffset = scheduleOffsets[index + 1];

			if (nextOffset) {
				return nextOffset - (offset + width);
			}
		}).filter(width => width);

		return restWidths
	} else {
		return []
	}

}

const calculateRestOffset = (scheduleWidths, scheduleOffsets) => {
	const hasRestPeriod = (scheduleWidths.length > 1);

	if (hasRestPeriod) {
		const restPeriodsLength = scheduleWidths.length - 1;

		const restOffsets =  scheduleWidths.map((width, index) => {
			if (index < restPeriodsLength) {
				return scheduleOffsets[index] + width;
			}
		}).filter(width => width);

		return restOffsets;
	} else {
		return []
	}
}

const translateToArray = (input) => {
	return (typeof input === 'string') ? input.split() : input;
}

export {
	calculateWidth,
	calculateOffset,
	calculateRestWidth,
	calculateRestOffset,
}